<?php

namespace App\Http\Controllers;

use App\Models\Demand;
use App\Models\Schedule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Repositories\ScheduleRepository;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Requests\Logic\Schedule\QueryResource;
use App\Http\Requests\Logic\Schedule\StoreResource;
use App\Http\Requests\Logic\Schedule\UpdateResource;
use App\Http\Requests\Logic\Schedule\DestroResource;
use App\Http\Requests\Logic\Schedule\QueryCollection;

/**
 * 排班逻辑控制器
 *
 * Date: 22/04/2018
 * @author George
 * @package App\Http\Controllers
 */
class ScheduleController extends Controller
{
    /**
     * 获取排班数据集合
     *
     * Date: 22/04/2018
     * @author George
     * @param QueryCollection $request
     * @return \Illuminate\Http\JsonResponse
     */
	public function index(QueryCollection $request)
	{
	    $user = Auth::user();
	    $user_id = $request->get('user_id');
	    $project_id = $request->get('project_id', $user->project->id);
	    $start = $request->get('start');
	    $end = $request->get('end');
	    $paginate = $request->get('paginate', 15);
	    $company_id = $user->company_id;

	    $query = Schedule::query()->with('project:id,name', 'user:id,name')->where('company_id', $company_id);

	    if ($user_id) {
	        $query->where('user_id', $user_id);
        }

        if ($project_id) {
            $query->where('project_id', $project_id);
        }

        if ($start && $end) {
	        $query->whereBetween('start',[$start, $end])->whereBetween('end', [$start, $end]);
        }

        return success($query->paginate($paginate));
	}

    /**
     * 根据ID获取排班详情
     *
     * Date: 22/04/2018
     * @author George
     * @param QueryResource $request
     * @param Schedule $schedule
     * @return \Illuminate\Http\JsonResponse
     */
	public function show(QueryResource $request, Schedule $schedule)
	{
	    return success($schedule);
	}

	/**
	 * 创建排班记录
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param StoreResource $request
	 * @param ScheduleRepository $scheduleRepository
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function store(StoreResource $request, ScheduleRepository $scheduleRepository)
	{
		$attributes = $this->extractInputFromRules($request, $request->rules());
		if ($scheduleRepository->verification($attributes['project_id'], $attributes['demand_id'], $attributes['users_id']) > 0) {
			return failed('排班记录已存在');
		}

		$schedule = $scheduleRepository->store($attributes);

		return stored($schedule);
	}

    /**
     * 更新排班信息
     *
     * Date: 22/04/2018
     * @author George
     * @param UpdateResource $request
     * @param Schedule $schedule
     * @return \Illuminate\Http\JsonResponse
     */
	public function update(UpdateResource $request, Schedule $schedule)
	{
	    $attributes = $this->extractInputFromRules($request, $request->rules());
	    $schedule->update($attributes);
	    return updated($attributes);
	}

    /**
     * 删除排班信息
     *
     * Date: 22/04/2018
     * @author George
     * @param DestroResource $request
     * @param Schedule $schedule
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
	public function destroy(DestroResource $request, Schedule $schedule)
	{
	    $schedule->delete();
	    return deleted();
	}

    /**
     * 验证给定日期是否存在
     *
     * Date: 21/04/2018
     * @author George
     * @param $user_id
     * @param string $start
     * @param string $end
     * @return bool
     */
	protected function leisure($user_id, string $start, string $end)
    {
        $count =  Schedule::query()->select(['id'])
            ->where('user_id', $user_id)
            ->whereBetween('start', [$start, $end])
            ->whereBetween('end', [$start, $end])
            ->count();
        return $count > 0 ? false : true;
    }

	/**
	 * 按天获取项目排班详情
	 *
	 * Date: 04/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function day(Request $request)
	{
		// 表单验证
		$this->validate($request, [
			'date' => 'required',
			'project_id' => 'required'
		]);
		$date = $request->get('date');
		$project_id = $request->get('project_id');

		// 定义返回数据格式
		$data = [
			'date' => $date
		];

		$damends = Demand::with(['genre' => function ($query) use ($date) {
			/**
			 * @var Builder $query
			 */
			$query->select(['id', 'name'])->with(['schedules' => function ($build) use ($date) {
				/**
				 * @var Builder $build
				 */
				$build->select(['id', 'user_id', 'line_id', 'genre_id', 'date', 'worktime'])
					->whereDate('schedules.date', $date)
					->with('user:id,name', 'line:id,name');
			}]);
		}])->whereDate('date', $date)->where('project_id', $project_id)->get();

		// 汇总需求人数
		$data['staff'] = $damends->sum(function ($demand) {
			return $demand->staff;
		});

		// 汇总已排人数
		$data['scheduled'] = $damends->sum(function ($demand) {
			return $demand->genre->schedules->count();
		});

		$data['demands'] = $damends;

		return success($data);
    }

	/**
	 * 获取未排班用户
	 *
	 * Date: 07/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function unschedule(Request $request)
	{
		$date = $request->get('date');
		$project_id = $request->get('project_id');

		$scheduled_users = DB::table('projects')->select('users.id')
			->leftJoin('users', 'projects.id', '=', 'users.project_id')
			->leftJoin('schedules', 'users.id', '=', 'schedules.user_id')
			->where('projects.id', $project_id)
			->whereDate('schedules.date', $date)
			->pluck('id');

		$users = DB::table('users')
			->where('users.project_id', $project_id)
			->whereNotIn('users.id', $scheduled_users)
			->select(['users.id', 'users.name', 'positions.name as position'])
			->leftJoin('positions', 'users.position_id', '=', 'positions.id')
			->get();

		return success($users);
    }

	/**
	 * 获取项目单月已排班时长
	 *
	 * Date: 05/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function times(Request $request)
	{
		$this->validate($request, [
			'month' => 'required',
			'project_id' => 'required'
		]);
		$month = $request->get('month');
		$project_id = $request->get('project_id');

		$start = date("{$month}-01");
		$end = date("{$month}-t");

		$times = Schedule::query()->whereBetween('date', [$start, $end])
			->where('project_id', $project_id)->sum('worktime');

		return success([
			'times' => $times / 3600
		]);
    }

	/**
	 * 获取排班的班次信息
	 *
	 * Date: 2018/6/22
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function scheduleOfGenre(Request $request)
	{
		$attributes = $this->validate($request, [
			'project_id' => 'required',
			'user_id' => 'required',
			'start' => 'required',
			'end' => 'required',
		]);
		$schedules = DB::table('schedules')
			->select(['date', 'name'])
			->leftJoin('genres', 'schedules.genre_id', '=', 'genres.id')
			->where([
				['schedules.project_id', '=', $attributes['project_id']],
				['user_id', '=', $attributes['user_id']],
			])->whereBetween('date', [$attributes['start'], $attributes['end']])->get();

		return success($schedules);
    }
}
